var TypeName = {
    vegetable: '蔬',
    pig: '猪',
    sheep: '羊',
    cattle: '牛',
    grain: '麦',
    wood: '木',
    clay: '泥',
    reed: '芦',
    stone: '石',
    food: '食'
}

var TypeFullName = {
    vegetable: '蔬菜',
    pig: '猪',
    sheep: '羊',
    cattle: '牛',
    grain: '小麦',
    wood: '木材',
    clay: '泥块',
    reed: '芦苇',
    stone: '石材',
    food: '食物'
}

window.boardData = {
    currentRound: 1,  // 初始化轮次为1
    // travelingPlayersFood:0, // 卖艺获得食物
    forest: 0, // 森林木材
    'clay-pit': 0, // 黏土坑泥块
    'reed-bank': 0, // 芦苇池
    fishing: 0, // 钓鱼
    // coppice:0, // 林地
    // grove:0, // 树林
    // clayPit2:0, // 泥坑
    // sheep-market:0, // 羊市
}

window.myData = {
    wood: 0,
    clay: 0, // 泥块
    reed: 0, // 芦苇
    stone: 0,
    grain: 0,
    vegetable: 0,
    food: 2,
    sheep: 0,
    pig: 0,
    cattle: 0,
    unusedWorker: 2,
    totalWorkers: 2,
    leftFences: 15,
    leftStables: 4,
    farmCells: createNewFarm(),
    roomType: "woodenHut", // woodenHut 木屋 / clayHut 砖房 / stoneHouse 石屋
    pastures: [],
    currentPasture: [],
    currentPastureWoodCost: 0,
    leftFencesBeforeBuildingFences: 0, // 建造栅栏之前记录剩余的栅栏数
    developmentCards: [], // 已建造的主要发展卡
    minorDevelopmentCards: [],  // 已打出的次要发展卡
    minorDevelopmentCardsInHand: [], // 手牌中的次要发展卡
    occupationCards: [], // 已打出的职业卡
    occupationCardsInHand: [], // 手牌中的职业卡
    disadvantages: 0, // 劣势
    newborns: [], // 用来记录婴儿的列表
    score: 0, // 在游戏过程中获得的分数
    workersWorkspaces: [], // 用于记录工人去的具体工位的 id
    roundRewards: Array(14).fill(null).map(() => ({})), // 记录水井以及其他卡牌在未来轮次牌上放置的资源奖励
}

window.actionData = {
    status: null, // buildRooms 建造房屋 / plowingFields 犁田 / buildingFences 建造栅栏
    moveAnimal: null, // 需要移动的动物的信息
    substatus: [], // bakeBread 烤面包 / sowingSeeds 播种 / plowingFields 犁田
    foodToPayDuringFeedingPhase: 0,
    statusStack: [], // 当有其他状态需要打断当前状态的流程时，需要先入栈当前状态，等到其他状态结算完毕再出栈恢复
    usedCells: 0, // 当前行动变为已使用的格子
}

function generateTurnCardHtml(options) {
    const {turnNum, id, onClick, title, content } = options;

    // HTML模板
    const template = `
    <div class="turn-work-space work-space-border" id="${id}" onclick="${onClick}">
        <div class="turn-work-space-with-2-column">
            <div class="turn-work-space-left">
                <div class="work-space-title">
                    第${turnNum}轮 ${title}
                </div>
                <p>
                    ${content}
                </p>
            </div>
            <div class="turn-work-space-right"></div>
        </div>        
    </div>
    `;

    return template;
}

function generateTurnCard(id, turnNum) {
    return allTurnCards[id].func(turnNum, id);
}

function initTurnCard(id) {
    var initFunc = allTurnCards[id].init;
    if (initFunc) {
        initFunc(id);
    }
}

const allTurnCards = {
    'development-card': {
        id: 'development-card',
        func: function (turnNum, id) {
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: 'selectDevelopmentCard()',
                title: `发展卡`,
                content: '打出1主要 或 次要发展卡'
            });
        }
    },
    'grain-utilization': {
        id: 'grain-utilization',
        func: function (turnNum, id) {
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: 'selectGrainUtilization()',
                title: `运用谷物`,
                content: '播种 和/或 烤面包'
            });
        }
    },
    'building-Fences': {
        id: 'building-Fences',
        func: function (turnNum, id) {
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: 'selectBuildingFences()',
                title: `围栏`,
                content: '建造栅栏 1木头=1栅栏'
            });
        }
    },
    'sheep-market': {
        id: 'sheep-market',
        func: function (turnNum, id) {
            const onClick = `selectResourceByKey('${id}')`;
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: onClick,
                title: `羊市`,
                content: '+1羊>>>'
            });
        },
        init: function (id) {
            window.boardData[id] = 0; // 从这一轮之后该积累格开始增长
        }
    },
    'add-family-member': {
        id: 'add-family-member',
        func: function (turnNum, id) {
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: 'selectAddFamilyMember()',
                title: `希望增加家庭成员`,
                content: '获得新成员，需要空房间。然后打出1次要发展卡'
            });
        }
    },
    'west-stone-quarry': {
        id: 'west-stone-quarry',
        func: function (turnNum, id) {
            const onClick = `selectResourceByKey('${id}')`;
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: onClick,
                title: `西采石场`,
                content: '+1石>>>'
            });
        },
        init: function (id) {
            window.boardData[id] = 0; // 从这一轮之后该积累格开始增长
        }
    },
    'house-renovation': {
        id: 'house-renovation',
        func: function (turnNum, id) {
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: 'selectHouseRenovation()',
                title: `房屋改建`,
                content: '1次翻新：1芦+x泥->x砖房；1芦+x石->x石屋。然后打出1主要 或 次要发展卡'
            });
        }
    },
    'pig-market': {
        id: 'pig-market',
        func: function (turnNum, id) {
            const onClick = `selectResourceByKey('${id}')`;
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: onClick,
                title: `猪市`,
                content: '+1猪>>>'
            });
        },
        init: function (id) {
            window.boardData[id] = 0; // 从这一轮之后该积累格开始增长
        }
    },
    'vegetable-seed': {
        id: 'vegetable-seed',
        func: function (turnNum, id) {
            const onClick = `selectResourceByKey('${id}')`;
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: onClick,
                title: `蔬菜种子`,
                content: '+1蔬菜'
            });
        }
    },
    'east-stone-quarry': {
        id: 'east-stone-quarry',
        func: function (turnNum, id) {
            const onClick = `selectResourceByKey('${id}')`;
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: onClick,
                title: `东采石场`,
                content: '+1石>>>'
            });
        },
        init: function (id) {
            window.boardData[id] = 0; // 从这一轮之后该积累格开始增长
        }
    },
    'cattle-market': {
        id: 'cattle-market',
        func: function (turnNum, id) {
            const onClick = `selectResourceByKey('${id}')`;
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: onClick,
                title: `牛市`,
                content: '+1牛>>>'
            });
        },
        init: function (id) {
            window.boardData[id] = 0; // 从这一轮之后该积累格开始增长
        }
    },
    'desire-add-family-member': {
        id: 'desire-add-family-member',
        func: function (turnNum, id) {
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: "selectDesireAddFamilyMember()",
                title: `渴望增加家庭成员`,
                content: '获得新成员，无需空房间。'
            });
        }
    },
    'farming': {
        id: 'farming',
        func: function (turnNum, id) {
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: 'selectFarming()',
                title: `耕种`,
                content: '犁1块田 和/或 播种'
            });
        }
    },
    'farm-renovation': {
        id: 'farm-renovation',
        func: function (turnNum, id) {
            return generateTurnCardHtml({
                turnNum: turnNum,
                id: id,
                onClick: 'selectFarmRenovation()',
                title: `农场改建`,
                content: '1次翻新：1芦+x泥->x砖房；1芦+x石->x石屋。然后建造栅栏 1木头=1栅栏'
            });
        }
    }
};

var turnCardsIdList = [
    'development-card',
    'grain-utilization',
    'building-Fences',
    'sheep-market',
    'add-family-member',
    'west-stone-quarry',
    'house-renovation',
    'pig-market',
    'vegetable-seed',
    'east-stone-quarry',
    'cattle-market',
    'desire-add-family-member',
    'farming',
    'farm-renovation'
];

function shuffleGroupWise(array) {
    // 分组
    let group1 = array.slice(0, 4);
    let group2 = array.slice(4, 7);
    let group3 = array.slice(7, 9);
    let group4 = array.slice(9, 11);
    let group5 = array.slice(11, 13);
    let group6 = array.slice(13, 14);

    // 打乱组内顺序
    group1 = shuffle(group1);
    group2 = shuffle(group2);
    group3 = shuffle(group3);
    group4 = shuffle(group4);
    group5 = shuffle(group5);

    // 合并所有组
    return [...group1, ...group2, ...group3, ...group4, ...group5, ...group6];
}

window.onload = function () {
    initAllPromptViews();
    if (localStorage.getItem('agricolaGameState')) {
        loadGame(); // 如果有存档则加载存档
    } else {
        updateResourceBar();
        updateFarm();
        turnCardsIdList = shuffleGroupWise(turnCardsIdList);
        initializeCards('minorDevelopment');  // 初始化次要发展卡
        initializeCards('occupation'); // 初始化职业牌
        step1(window.boardData.currentRound);  // 使用当前轮次开始
        updateFutureRoundRewards();
    }
    pageScrollToTop();
};

//------------ 存档和读档
function saveGame() {
    const gameState = {
        boardData: window.boardData,
        myData: window.myData,
        turnCardsIdList: turnCardsIdList
    };
    localStorage.setItem('agricolaGameState', JSON.stringify(gameState));
}

function loadGame() {
    const gameState = localStorage.getItem('agricolaGameState');
    if (gameState) {
        const parsedState = JSON.parse(gameState);
        window.boardData = parsedState.boardData;
        window.myData = parsedState.myData;
        turnCardsIdList = parsedState.turnCardsIdList;

        restoreTurnCards(turnCardsIdList.slice(0, window.boardData.currentRound));
        updateResourceBar();
        updateAllAccumulationResource();
        updateFarm();
        updateAdditionalView();
        restoreDevelopmentCards();
        updateCardsInHand('minorDevelopment');
        restoreCards('minorDevelopment');
        updateCardsInHand('occupation');
        restoreCards('occupation');
        updateFutureRoundRewards();
    }
}

function removeGame() {
    localStorage.removeItem('agricolaGameState');
}

function newGame() {
    if (!confirm('确定开始新游戏？')) {
        return;
    }
    localStorage.removeItem('agricolaGameState');
    location.reload();
}